<template>
  <div class="app-container">

  <div v-if="progress > 0" class="progress-bar">
  <div class="inner" :style="{ width: `${progress}%` }"></div>
  <span class="text">{{ progress }}%</span>
  <span class="estimated-time" v-if="estimatedTime">预计完成时间: {{ estimatedTime }}</span>
</div>
    
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编码" prop="equipmentCode">
        <el-input v-model="queryParams.equipmentCode" placeholder="请输入设备编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="型号" prop="modelId">
        <el-input v-model="queryParams.modelId" placeholder="请输入型号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品类型" prop="productTypeId">
        <el-input v-model="queryParams.productTypeId" placeholder="请输入产品类型" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:equipment:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:equipment:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:equipment:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:equipment:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="设别状态" align="center" prop="equipmentStatus">
        <template #default="{ row }">
          <span class="status-cell">
            <span class="status-dot" :class="row.equipmentStatus === 0 ? 'active' : 'inactive'"></span>
            {{ row.equipmentStatus === 0 ? '启用' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="设备编码" align="center" prop="equipmentCode" />
      <el-table-column label="设备名称" align="center" prop="equipmentName">
        <template #default="{ row }">
          <a @click="handleDetail(row)" style="color:cornflowerblue;">{{ row.equipmentName }}</a>
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="modelName" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品类型" align="center" prop="productTypeName" />
      <el-table-column label="设备绑定数量" align="center" prop="vehicleCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:equipment:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:equipment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="equipmentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品类型" prop="productTypeId">
          <el-select v-model="form.productTypeId" placeholder="请选择" style="width: 240px">
            <el-option v-for="item in productData" :key="item.id" :label="item.productName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>


        <el-form-item label="设备型号" prop="modelId">
          <el-input v-model="form.modelId" placeholder="请输入型号" />
        </el-form-item>
         <el-form-item label="图片" prop="equipmentImage">
          <image-upload v-model="form.equipmentImage"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>




    <el-dialog v-model="dialogFormVisible" title="设备信息" width="500">
      <h3 style="font-weight: bold; ;">基本信息</h3>
      <div class="center-content">
        <div class="device-info-item">
          <span style="font-weight: bold; margin-left: 60px;">设备型号:</span>
          <span style="margin-left: 20px;">{{ form.modelName }}</span>
        </div>
        <div class="device-info-item">
          <span style="font-weight: bold; margin-left: 60px;">产品类型:</span>
          <span style="margin-left: 20px;">{{ form.productTypeName }}</span>
        </div>
        <div class="device-info-item">
          <span style="font-weight: bold; margin-left: 60px;">产品名称:</span>
          <span style="margin-left: 20px;">{{ form.productName }}</span>
        </div>
        <div class="device-info-item">
          <span style="font-weight: bold; margin-left: 60px;">备注:</span>
          <span style="margin-left: 20px;">{{ form.remark }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">

          <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog - dialog>
  </div>
</template>

<script setup>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment } from "@/api/system/equipment";
import { listProduct } from "@/api/system/product";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const dialogFormVisible = ref(false)

const equipmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const productData = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentStatus: null,
    equipmentCode: null,
    equipmentName: null,
    modelId: null,
    productName: null,
    productTypeId: null
  },
  rules: {
  }
});
import { Plus } from '@element-plus/icons-vue'

import axios from 'axios';

const imageUrl = ref('')

const handleAvatarSuccess = (response, uploadFile) => {
  console.log(uploadFile.response)
  form.value.equipmentImage = uploadFile.response

  console.log(form.value.equipmentImage)

};

const { queryParams, form, rules } = toRefs(data);

/** 查询设备列表 */
function getList() {
  loading.value = true;
  listEquipment(queryParams.value).then(response => {
    equipmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleDetail(row) {
  dialogFormVisible.value = true
  form.value = row
}
function getProductList() {
  listProduct().then(response => {
    console.log(response)
    productData.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    equipmentStatus: null,
    equipmentCode: null,
    equipmentName: null,
    modelId: null,
    productName: null,
    productTypeId: null,
    equipmentImage: null
  };
  proxy.resetForm("equipmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {

  reset();
  getProductList();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getEquipment(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["equipmentRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateEquipment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEquipment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备编号为"' + _ids + '"的数据项？').then(function () {
    return delEquipment(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
const progress = ref(0); // 0-100 的进度值
const estimatedTime = ref(''); // 预计完成时间

async function handleExport() {
  try {
    // 初始化进度
    progress.value = 1; // 从1%开始避免进度条闪烁
    estimatedTime.value = '正在计算...';
    
    let startTime = Date.now();
    let lastLoaded = 0;
    let hasContentLength = false;

    const response = await proxy.download(
      'system/equipment/export',
      queryParams.value,
      `equipment_${new Date().getTime()}.xlsx`,
      {
        onDownloadProgress: (progressEvent) => {
          // 处理未知内容长度的情况
          if (progressEvent.total === 0) {
            hasContentLength = false;
            // 模拟进度（当后端没有返回Content-Length时）
            progress.value = Math.min(progress.value + 1, 98);
            estimatedTime.value = '剩余时间未知';
            return;
          }

          hasContentLength = true;
          const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
          progress.value = Math.min(percent, 99); // 留1%给完成状态

          // 计算剩余时间
          const currentTime = Date.now();
          const timeDiff = (currentTime - startTime) / 1000;
          const loadedDiff = progressEvent.loaded - lastLoaded;
          const speed = loadedDiff / timeDiff;

          if (speed > 0) {
            const remainingBytes = progressEvent.total - progressEvent.loaded;
            const remainingTime = remainingBytes / speed;
            estimatedTime.value = formatTime(remainingTime);
          }

          lastLoaded = progressEvent.loaded;
          startTime = currentTime;
        }
      }
    );

    // 下载完成时设置100%
    progress.value = 100;
    estimatedTime.value = '已完成';

    // 2秒后隐藏进度条
    setTimeout(() => {
      progress.value = 0;
      estimatedTime.value = '';
    }, 2000);

  } catch (error) {
    console.error('下载失败:', error);
    progress.value = 0;
    estimatedTime.value = '导出失败';
    setTimeout(() => {
      estimatedTime.value = '';
    }, 2000);
  }
}
// 下载完成后设置进度为 100%
progress.value = 100;
estimatedTime.value = '完成';

// 延迟隐藏进度条
setTimeout(() => {
  progress.value = 0;
  estimatedTime.value = '';
}, 1000); // 延迟 1 秒隐藏
// 格式化时间（秒 -> 分钟:秒）
function formatTime(seconds) {
  if (isNaN(seconds) )return '计算中...';
  if (seconds <= 0) return '即将完成';

  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);

  return `${minutes} 分 ${remainingSeconds} 秒`;
}
onMounted(() => {
  progress.value = 0; // 重置进度条
  estimatedTime.value = ''; // 重置预计完成时间
});

getList();
</script>
<style scoped>
.status-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  /* 添加这一行以实现水平居中 */
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
}

.status-dot.active {
  background-color: green;
}

.status-dot.inactive {
  background-color: red;
}




.status-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
}

.status-dot.active {
  background-color: green;
}

.status-dot.inactive {
  background-color: red;
}


.center-content {
  padding: 20px;
}

.device-info-item {
  margin-bottom: 10px;
}



.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}


.progress-bar {
  position: fixed;
  top: 50px; /* 下移避免被导航栏遮挡 */
  left: 50%;
  transform: translateX(-50%);
  z-index: 2000; /* 确保高于其他元素 */
  width: 600px;
  height: 40px;
  background: #f8f8f8;
  border: 1px solid #e6e6e6;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  padding: 0 15px;
}

.inner {
  transition: width 0.3s ease;
  height: 70%;
  border-radius: 15px;
}

.text {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-weight: bold;
  color: green;
  text-shadow: 0 1px 2px rgba(0,0,0,0.2);
}

.estimated-time {
  position: absolute;
  right: 15px;
  font-size: 12px;
  color: #666;
}
</style>